/**
* 音频处理工具
*/

(function(win, $){
    var module = {};

    /**
     * 播放音频
     * @param {Object} path
     */
    module.playAudio = function(path) {
        var player = plus.audio.createPlayer(path);
        player.play(function(){
            // mui.toast("播放成功");
        }, function(e) {
            mui.toast("播放失败");
        }); 
    }

    /**
     * 录音语音文件转base64字符串
     * @param {Object} path
     */
    module.Audio2dataURL = function(path, callback) {
        plus.io.resolveLocalFileSystemURL(path, function(entry){
            entry.file(function(file){
                var reader = new plus.io.FileReader();
                reader.onloadend = function (e) {
                    var base64Str = e.target.result.replace('data:audio/amr;base64,','');
                    callback(base64Str)
                };
                reader.readAsDataURL(file);
            },function(e){
                mui.toast("读写出现异常: " + e.message );
            })
        })
    }

    /**
     * base64字符串转成语音文件(参考http://ask.dcloud.net.cn/question/16935)
     * @param {Object} base64Str
     * @param {Object} callback
     */
    module.dataURL2Audio = function(base64Str, callback) {
        var base64Str = base64Str.replace('data:audio/amr;base64,','');
        var audioName = (new Date()).valueOf() + '.amr';

        plus.io.requestFileSystem(plus.io.PRIVATE_DOC,function(fs){
            fs.root.getFile(audioName,{create:true},function(entry){
                // 获得平台绝对路径
                var fullPath = entry.fullPath;
                if(mui.os.android){  
                    // 读取音频
                    var Base64 = plus.android.importClass("android.util.Base64");
                    var FileOutputStream = plus.android.importClass("java.io.FileOutputStream");
                    try{
                        var out = new FileOutputStream(fullPath);
                        var bytes = Base64.decode(base64Str, Base64.DEFAULT);
                        out.write(bytes); 
                        out.close();
                        // 回调
                        callback && callback(entry);
                    }catch(e){
                        console.log(e.message);
                    }
                }else if(mui.os.ios){
                    var NSData = plus.ios.importClass('NSData');
                    var nsData = new NSData();
                    nsData = nsData.initWithBase64EncodedStringoptions(base64Str,0);
                    if (nsData) {
                        nsData.plusCallMethod({writeToFile: fullPath,atomically:true});
                        plus.ios.deleteObject(nsData);
                    }
                    // 回调
                    callback && callback(entry);
                }
            })
        })
    }

    win.audioUnitl = module;
})(window, jQuery)